<script setup lang="ts">
import Write from './components/Write.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ref, unref } from 'vue'
import { ElButton } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { useRouter, useRoute } from 'vue-router'
import { saveTableApi, getViewApi1 } from '@/api/lunbotu'
import type { AdverData } from '@/api/lunbotu/types'
import { useEmitt } from '@/hooks/web/useEmitt'

const { emitter } = useEmitt()

const { push } = useRouter()

const { query } = useRoute()

const { t } = useI18n()

const currentRow = ref<Nullable<AdverData>>(null)

const getTableDet = async () => {
  const res = await getViewApi1(query.carousel_id as string)
  if (res) {
    /*res.data.map(function (val) {
      if (val.img_type == 1) {
        val.img_type = '商品'
      } else if (val.img_type == 2) {
        val.img_type = '视频'
      } else if (val.img_type == 3) {
        val.img_type = '其他'
      }
      if (val.display == 1) {
        val.display = '显示'
      } else if (val.display == 2) {
        val.display = '不显示'
      }
    })*/
    currentRow.value = res.data[0]
  }
}

getTableDet()

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const validate = await write?.elFormRef?.validate()?.catch(() => {})
  if (validate) {
    loading.value = true
    const data = (await write?.getFormData()) as AdverData
    console.log(data)
    const res = await saveTableApi(data)
      .catch(() => {})
      .finally(() => {
        loading.value = false
      })
    if (res) {
      emitter.emit('getList', 'edit')
      push('/rotograph/advertisement')
    }
  }
}
</script>

<template>
  <ContentDetailWrap :title="t('exampleDemo.edit')" @back="push('/rotograph/advertisement')">
    <Write ref="writeRef" :currentRow="currentRow" />

    <template #right>
      <ElButton type="primary" :loading="loading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
    </template>

    <template #imgAddress="{ row }: { row: AdverData }">
      <img :src="row.imgAddress" width="200" height="200" />
    </template>
  </ContentDetailWrap>
</template>
